'use strict'

define(function (require, exports, module) {
    var angular = require('angular');
    var dialog = require("dialogplus");
    require("/public/js/plugins/select2/select2");
    var util = require("util");
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀
    require('/public/js/myservice/contract/contract-common');
    var myMath = require('/public/js/myservice/common/my-math');

    var ContractReceivableInvoice = angular.module('ContractReceivableInvoice', ['ContractCommonService']);

    ContractReceivableInvoice.service('receivableInvoiceService', ['$rootScope', 'contractCommonService', function ($rootScope, contractCommonService) {
        $rootScope.invoiceInfo = {};
        $rootScope.editFunds = [];
        var service = {
            onInvoiceEditShow: function ($data, $dialog, $dialogScope, invoiceType, oldInvoice) {
                /**
                 * 打开发票编辑界面时初始化
                 * invoiceType: 发票类型：1：发票，2：子发票，3：红冲发票，4：收据
                 * oldInvoice: 原发票
                 */

                    //新建发票
                $dialogScope.invoiceInfo = {
                    invoiceSummarys: [],
                    contract_id: $data,
                    is_receipt: invoiceType == 4 ? 1 : 0,
                    is_red_invoice: invoiceType == 3 ? 1 : 0,
                    is_child_invoice: invoiceType == 2 ? 1 : 0,
                    is_main_invoice: 0
                };

                //开票金额变更时，重新计算分摊金额
                $dialogScope.$watch('invoiceInfo.invoice_amount', function () {
                    $dialogScope.shareAmount();
                });

                //分摊发票金额
                $dialogScope.shareAmount = function () {
                    var items = $dialogScope.editInvoiceReceivables || [];
                    var invoiceAmount = ($dialogScope.invoiceInfo.invoice_amount || 0) - ($dialogScope.invoiceInfo.receivables_amount || 0);
                    $.each(items, function (i, d) {
                        if (!d._checked || invoiceAmount <= 0) {
                            d.cur_billing_amount = 0;
                            return true;
                        }
                        d.cur_billing_amount = myMath.sub(d.receivable_amount, d.billing_amount);
                        invoiceAmount -= d.cur_billing_amount;
                        if (invoiceAmount < 0) {
                            d.cur_billing_amount += invoiceAmount;
                        }
                    });
                };

                $dialogScope.orgianlInvoice = oldInvoice;
                $dialogScope.invoiceType = invoiceType;
                $dialogScope.invoiceName = invoiceType == 4 ? '收据' : '发票';

                //下拉框设置
                //发票类别
                $dialogScope.ddlConfigInvoiceCategory = {
                    allowClear: false,
                    data: [{id: 1, text: '服务票'}, {id: 0, text: '销售票'}],
                    minimumResultsForSearch: 'Infinity'
                };

                //发票类型
                $dialogScope.ddlConfigInvoiceType = {
                    allowClear: false,
                    data: [{id: "0", text: '增值税普通发票'}, {id: "1", text: '增值税专用发票'}],
                    minimumResultsForSearch: 'Infinity'
                };

                //摘要类型
                $dialogScope.ddlConfigInvoiceSummaryType = {
                    allowClear: false,
                    data: [{id: '软件技术服务费', text: '软件技术服务费'}, {id: '软件服务费', text: '软件服务费'}],
                    minimumResultsForSearch: 'Infinity'
                };

                //申请人
                $dialogScope.ddlConfigInvoiceProposer = {
                    allowClear: false,
                    ajax: {
                        url: api_prefix + "erp-interface/get-users",
                        dataType: 'json',
                        delay: 250,
                        data: function (term) {
                            return {
                                keyword: term,
                                limit: 10
                            };
                        },
                        results: function (json, page) {
                            var data = [];
                            if (json.retCode === "0") {
                                data = json.data;
                            }
                            return {results: data};
                        },
                        cache: true
                    },
                    escapeMarkup: function (markup) {
                        return markup;
                    }, // let our custom formatter work
                    minimumInputLength: 1,
                    onchange2: function (newVal) {
                        $dialogScope.invoiceInfo.user_name = newVal.UserName;
                        $dialogScope.invoiceInfo.area_name = newVal.BUName;
                    }
                };
                //开票单位
                $dialogScope.ddlConfigInvoiceCompany = {
                    allowClear: false,
                    data: [],
                    onchange2: function (newVal) {
                        $dialogScope.invoiceInfo.invoice_company_name = newVal.BUName;
                    }
                };

                contractCommonService.getInvoiceBusinessUnit(function (data) {
                    var ddlData = [];
                    $.each(data, function (i, d) {
                        ddlData.push({id: d.BUGUID, text: d.BUName});
                    });
                    $dialogScope.ddlConfigInvoiceCompany.data = ddlData;
                    $dialogScope.$applyAsync();
                });

                //主发票ddl
                $dialogScope.ddlConfigMainInvoice = {
                    ajax: {
                        url: api_prefix + "receivable/get-parent-invoice-info",
                        dataType: 'json',
                        delay: 250,
                        data: function (term, page) {
                            return {
                                keyword: term, // search term
                                page: page
                            };
                        },
                        results: function (json, page) {
                            var data = [];
                            if (json.retCode == 0) {
                                data = json.data;
                                $.each(data, function (i, d) {
                                    d.id = d.invoice_id;
                                    d.text = d.invoice_no;
                                });
                            }
                            return {results: data};
                        },
                        cache: true
                    },
                    minimumInputLength: 1
                };

                //获取应收信息列表
                if (invoiceType != 3) {
                    //非红冲发票去应收信息
                    contractCommonService.getContractReceivable($data, function (json) {
                        $dialogScope.editInvoiceReceivables = json;
                        $dialogScope.$applyAsync();
                    });
                } else {
                    $dialogScope.invoiceInfo = angular.extend({}, oldInvoice);
                    $dialogScope.invoiceInfo.red_by_invoice_id = $dialogScope.invoiceInfo.invoice_id;
                    $dialogScope.invoiceInfo.invoice_id = null;//红冲发票新增记录
                    $dialogScope.invoiceInfo.is_red_invoice = 1;
                    $dialogScope.invoiceInfo.invoice_amount = -$dialogScope.invoiceInfo.invoice_amount;
                    setTimeout(function () {
                        $('.idInvoiceCompany:last').data('select2').updateSelection({text: oldInvoice.BUName || ''});
                        $('.idProposer:last').data('select2').updateSelection({text: oldInvoice.UserName || ''});
                        $('.idMainInvoice:visible').length && $('.idMainInvoice:visible').data('select2').updateSelection({text: oldInvoice.main_invoice_no});
                    }, 500);

                    $.each($dialogScope.invoiceInfo.invoiceSummarys, function (i, d) {
                        d.summary_amount = -Math.abs(d.summary_amount);
                    });
                }

                $dialogScope.totalEqualAmount = function () {
                    if ($dialogScope.invoiceInfo.invoice_amount) {
                        return $dialogScope.totalAmount() != $dialogScope.invoiceInfo.invoice_amount;
                    } else {
                        return false;
                    }
                };

                /**
                 * 计算摘要金额总和
                 * @returns {number}
                 */
                $dialogScope.totalAmount = function () {
                    var sum = 0;

                    var items = $dialogScope.invoiceInfo.invoiceSummarys;
                    if (items) {
                        for (var i = 0; i < items.length; i++) {
                            var item = items[i];
                            sum += parseFloat(item.summary_amount);
                        }
                    }

                    return sum;
                };

                //新建发票摘要
                $dialogScope.newInvoiceAbstract = function () {
                    var items = $dialogScope.invoiceInfo.invoiceSummarys;
                    var id;
                    id = items.length ? items[0].id + 1 : 1;
                    var summary = {
                        id: id,
                        summary_type: '软件技术服务费',
                        summary_amount: '0'
                    };
                    items.unshift(summary);
                };

                //删除发票摘要
                $dialogScope.removeInvoiceAbstract = function (idx) {
                    var item;
                    var items = $dialogScope.invoiceInfo.invoiceSummarys;
                    items.splice(idx, 1);
                };

                $dialogScope.vaildSummaryRequired = function () {
                    var items = $dialogScope.invoiceInfo.invoiceSummarys;
                    var rst = $.grep(items, function (d, i) {
                        return d.summary_amount == null;
                    })
                    return rst.length > 0;
                };
                $dialogScope.vaildSummaryNumber = function () {
                    var items = $dialogScope.invoiceInfo.invoiceSummarys;
                    var rst = $.grep(items, function (d, i) {
                        return d.summary_amount && !d.summary_amount.toString().match(/^-?[\d]*(\.[\d]+)*$/);
                    })
                    return rst.length > 0;
                };

                var self = this;
                $dialogScope.showInvoiceImport = function () {
                    self.onInvoiceImportShow($dialogScope, '引入未关联合同发票', $dialogScope.importInvoice);
                };
                $dialogScope.importInvoice = function (item) {
                    $dialogScope.invoiceInfo = angular.extend($dialogScope.invoiceInfo, angular.copy(item), {contract_id: $dialogScope.invoiceInfo.contract_id});
                    $dialogScope.$applyAsync();

                    setTimeout(function () {
                        $('.idProposer:visible').length && $('.idProposer:visible').data('select2').updateSelection({text: $dialogScope.invoiceInfo.UserName});
                        $('.idInvoiceCompany:visible').length && $('.idInvoiceCompany:visible').data('select2').updateSelection({text: $dialogScope.invoiceInfo.BUName});
                        $('.idMainInvoice:visible').length && $('.idMainInvoice:visible').data('select2').updateSelection({text: $dialogScope.invoiceInfo.main_invoice_no});
                    }, 100);
                }
            },
            onInvoiceImportShow: function ($dialogScope, title, callback) {
                /**
                 * 引入未关联合同界面初始化
                 */

                $dialogScope.importInvoices = [];

                contractCommonService.getCanUseInvoiceInfo($dialogScope.invoiceInfo.contract_id, function (data) {
                    $dialogScope.importInvoices = data;
                    $dialogScope.$applyAsync();
                });

                $dialogScope.selectInvoice = function (item) {
                    $.each($dialogScope.importInvoices, function (i, d) {
                        d.__selected = false;
                    })
                    item.__selected = true;
                };

                var d = dialog({
                    title: title,
                    content: $('.importInvoiceDlg:last'),
                    fixed: true,
                    width: 650,
                    height: 450,
                    okValue: "确定",
                    ok: function () {
                        var selectedInvoices = $.grep($dialogScope.importInvoices, function (d, i) {
                            return d.__selected == true;
                        })
                        if (selectedInvoices.length) {
                            if (callback && typeof callback == 'function') {
                                callback(selectedInvoices[0]);
                                $dialogScope.$applyAsync();
                            }
                        } else {
                            util.alert('请选择发票记录');
                            return false;
                        }

                        return true;
                    },
                    cancel: function () {
                    }
                });
                d.showModal();

            },
            editInvoiceSave: function ($data, $dialog, $dialogScope, callback) {
                /**
                 * 保存新增发票
                 */
                var invoiceInfo = $dialogScope.invoiceInfo;
                var checkedReceivables = $.grep($dialogScope.editInvoiceReceivables || [], function (d, i) {
                    return d._checked == true;
                })
                invoiceInfo.invoiceReceivables = checkedReceivables;

                //校验
                if ($('.error:visible').length) {
                    return false;
                }

                var post_data = invoiceInfo;
                var url;
                url = api_prefix + "/receivable/save-invoice-receivable";

                util.myAjax({
                    url: url,
                    type: "POST",
                    context: this,
                    data: post_data,
                    async: false,
                    success: function (json) {
                        if (json.retCode == 0) {
                            util.alert("保存成功");
                            if (callback) {
                                callback();
                            }
                            $dialog.close();
                        } else {
                            util.alert("保存失败：" + json.errMsg);
                            return false;
                        }
                    }
                });

                return false;
            },
            deleteInvoice: function (invoiceInfo, callback) {
                /**
                 * 删除发票
                 */
                util.confirm('确定要删除此发票吗?', {
                    ok: function () {
                        var post_data = {invoice_id: invoiceInfo.invoice_id};
                        var url;
                        url = api_prefix + "/receivable/delete-invoice";

                        util.myAjax({
                            url: url,
                            type: "POST",
                            context: this,
                            data: post_data,
                            success: function (json) {
                                if (json.retCode == 0) {
                                    invoiceInfo.__isdelete = 1;
                                    util.alert("删除成功");
                                    $rootScope.$applyAsync();
                                    if (callback) {
                                        callback();
                                    }
                                } else {
                                    util.alert("删除失败：" + json.errMsg);
                                }
                            }
                        });
                    }
                });
            },
            convertToInvoice: function (invoiceInfo) {
                /**
                 * 收据转为发票
                 */
                util.confirm('确定要把此收据转为发票吗?', {
                    ok: function () {
                        var post_data = angular.extend({}, invoiceInfo, {is_receipt: 0});
                        var url;
                        url = api_prefix + "/receivable/save-invoice-receivable";

                        util.myAjax({
                            url: url,
                            type: "POST",
                            context: this,
                            data: post_data,
                            success: function (json) {
                                if (json.retCode == 0) {
                                    invoiceInfo.is_receipt = 0;
                                    util.alert("收据转为发票成功");
                                    $rootScope.$applyAsync();
                                } else {
                                    util.alert("收据转为发票失败：" + json.errMsg);
                                }
                            }
                        });
                    }
                });
            }
        }
        return service;
    }]);

    module.exports = ContractReceivableInvoice;
});